import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import java.net.UnknownHostException;
import org.bson.types.ObjectId;

/**
 *
 * @author Code4LifeVn
 */
public class PhoneBookDAO implements IMongoDAO<PhoneBook> {
	private MongoClient mongoClient;
	private DB phoneBookDB;
	private DBCollection phoneBookListCollection;
	private ModelConverter<PhoneBook> converter;

	public PhoneBookDAO() throws UnknownHostException {
		mongoClient = new MongoClient("localhost", 27017);
		phoneBookDB = mongoClient.getDB("PhoneBook");
		phoneBookListCollection = phoneBookDB.getCollection("phone_book_list");
		converter = new PhoneBookConverter();
	}

	@Override
	public DBCollection getDBCollection() {
		return phoneBookListCollection;
	}

	@Override
	public void insert(PhoneBook object) {
		BasicDBObject newPhoneBook = converter
				.convertModelToBasicObject(object);
		phoneBookListCollection.insert(newPhoneBook);
	}

	@Override
	public PhoneBook readItem(DBObject object) {
		return converter.convertBasicObjectToModel((BasicDBObject) object);
	}

	@Override
	public void update(PhoneBook oldObject, PhoneBook newObj) {
		BasicDBObject old = new BasicDBObject("mobi", oldObject.getMobi());
		BasicDBObject query = new BasicDBObject().append("$set",
				new BasicDBObject().append("mobi", newObj.getMobi()));
		phoneBookListCollection.update(old, query, false, true);
	}

	@Override
	public void delete(PhoneBook object) {
		BasicDBObject query = new BasicDBObject("_id", new ObjectId(
				object.getId()));
		phoneBookListCollection.remove(query);
	}

	@Override
	public PhoneBook findDocumentById(String _id) {
		BasicDBObject obj = (BasicDBObject) phoneBookListCollection.find(
				new BasicDBObject("_id", new ObjectId(_id))).next();
		return converter.convertBasicObjectToModel(obj);
	}
}